import json
from sqlite3 import dbapi2
from flask import Flask, jsonify, render_template, request, redirect
from matplotlib.style import use
from OLD.applications import redire
import dbAction
import functions

app = Flask(__name__)

@app.route("/")
def index():
    return 'hello'

'''
    取所有用户，返回json or html 
'''
@app.route("/getusers")
def getAll():
    # jsonify(functions.jsonMade(200,dbAction.getuser(),'success'))
    return render_template("index.html",data = dbAction.getuser())
'''
    根据ID取用户
'''
@app.route("/getuserbyid/<int:id>")
def getuserbyid(id):
    return jsonify(functions.jsonMade(200,dbAction.getuserbyid(id),'success'))

'''
    添加用户
'''
@app.route("/adduser",methods = ['GET','POST'])
def adduser():
    if request.method == 'GET':
        return render_template("add.html")
    if request.method == 'POST':
        dbAction.adduser(request.form.get('name'),request.form.get('age'))
        return redirect("/getusers")

'''
    删除用户
'''
@app.route("/deleteuser/<int:id>")
def deleteuser(id):
    dbAction.deleteuser(id)
    return redirect("/getusers")

'''
    更新用户
'''
@app.route("/update/<int:id>",methods = ['GET','POST'])
def updateuser(id):
    if request.method == 'GET':
        if functions.checkIdExist(id) == True :
            userdata = dbAction.getuserbyid(id)          
            return render_template("update.html",data = userdata)
        else:
            return redirect("/getusers")
    if request.method == 'POST':
        id = request.form.get('id')
        name = request.form.get('name')
        age = request.form.get('age')
        print(dbAction.updateuser(id,name,age))
        return redirect("/getusers")



if __name__ == '__main__':
    app.run( debug= True)